// pages/cleanUp/cleanUp.js
const app = getApp();
const utils = require('../../utils/util.js');
const post = utils.post;
const getCurrentPageUrlWithArgs = utils.getCurrentPageUrlWithArgs;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        z_uid: '',
        m_uid: '',
        list: [],
        show_count_money: 0,
        weapp_status: 0,
        //flag: false,
        //sy: 0,
        // 跑马灯
        WrittenBy: '',
        width: '',
        marqueePace: 1, //滚动速度
        marqueeDistance: 0, //初始滚动距离
        marqueeDistance2: 0,
        marquee2copy_status: false,
        marquee2_margin: 60,
        size: 14,
        orientation: 'left', //滚动方向
        interval: 30, // 时间间隔
        result: [],
        share_wxfx: true,
        share_wx_bg: false,
        share_img: true,
        ifName: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        wx.hideShareMenu();
        let that = this;
        wx.getSystemInfo({
            success: function(res) {
                //console.log(res.system)
                let dataList = res.system.toLowerCase(); //获取到的数据
                //console.log(dataList)
                if (/^ios/.test(dataList)) {
                    that.setData({
                        issystem: true
                    });
                } else if (/^android/.test(dataList)) {
                    that.setData({
                        issystem: false
                    });
                }
            }
        })
       /* let p0 = {
            m: 'weapp_status',
            v: 3
        };*/
        let p0 = {
            m: 'weapp_statusx',
            v: 1,
            name:'xzz'
        };
        post(p0).then(res => {
            that.setData({
                weapp_status: res.status
            });

            if (1 == that.data.weapp_status) { // 审核通过了 
                wx.showToast({
                    icon: 'loading',
                    duration: 500
                });

                that.doGetUserInfo(options);
            }
        });
    },

    doGetUserInfo(options) {
        let that = this;
        var _userinfo = wx.getStorageSync('_userinfo');
        var weapp_openid = wx.getStorageSync('weapp_openid');
        if (_userinfo && weapp_openid && weapp_openid == _userinfo.openId) {
            that.doLogin(options);
        } else {
            // 获取用户信息
            wx.login({
                success(res) {
                    // console.log(res);

                    var code = res.code;
                    wx.getUserInfo({
                        success(res2) {
                            // console.log(res2)
                            var encryptedData = res2.encryptedData;
                            var iv = res2.iv;
                            var p = {
                                m: 's_get_userinfo',
                                code: code,
                                encryptedData: encryptedData,
                                iv: iv
                            };
                            post(p).then(res3 => {
                                if (0 == res3.r) {
                                    // console.log(res3);
                                    var userinfo = res3.userinfo;
                                    var weapp_openid = userinfo.openId;
                                    wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId
                                    wx.setStorageSync('_userinfo', res3.userinfo);
                                    wx.setStorageSync('device_info', wx.getSystemInfoSync());

                                    wx.showToast({
                                        title: '登录成功',
                                        icon: 'none'
                                    });

                                    that.doLogin(options);
                                }
                            })
                        }
                    })
                }
            })
        }
    },

    doLogin(params) {
        // console.log(params)
        let that = this;
        var z_uid = wx.getStorageSync("z_uid"); // 对应赚客login_id
        var m_uid = wx.getStorageSync("m_uid"); // 对应赚客用户uid
        if (z_uid && m_uid) {
            that.onShow();
        } else {
            var z_uid = params.z_uid;
            var m_uid = params.m_uid;
            if (z_uid && m_uid) {
                wx.setStorageSync('z_uid', z_uid);
                wx.setStorageSync('m_uid', m_uid);

                that.onShow();
            } else {
                var phone = params.phone; //手机号
                var reg = /^1(0|1|2|3|4|5|6|7|8|9)\d{9}$/;
                if (!phone || !reg.test(phone)) {
                    wx.showModal({
                        content: '手机号码不合法，无法使用',
                        showCancel: false
                    });

                    return;
                }
                let p = {};

                var _from = params.from;
                if (_from && 'zhuanke' == _from) { // 从小程序推送过来的
                    p = {
                        m: 's_login',
                        phone: phone,
                        login_name: _from
                    };
                } else { // 从赚多多APP过来的
                    var channel = params.channel; //渠道号
                    if (!channel) {
                        wx.showModal({
                            content: '渠道为空，无法使用',
                            showCancel: false
                        });

                        return;
                    }

                    var third_uid = params.third_uid; //用户的uid
                    if (!third_uid) {
                        wx.showModal({
                            content: '第三方用户uid为空，无法使用',
                            showCancel: false
                        });

                        return;
                    }

                    p = {
                        m: 's_login',
                        phone: phone,
                        channel: channel,
                        third_uid: third_uid,
                    };

                    var _userinfo = wx.getStorageSync('_userinfo');
                    var weapp_openid = wx.getStorageSync('weapp_openid');
                    if (_userinfo && weapp_openid && weapp_openid == _userinfo.openId) {
                        p.userinfo = JSON.stringify(_userinfo);
                    }

                    if (params.third_t_uid) {
                        p.third_t_uid = params.third_t_uid; //师傅的uid
                    }
                }

                post(p).then(res => {
                    //console.log(res)
                    if (0 == res.r) {
                        wx.setStorageSync("z_uid", res.uid); // 对应赚客手机号
                        wx.setStorageSync("m_uid", res.m_uid); // 对应赚客用户uid

                        that.onShow();
                    } else {
                        wx.navigateTo({
                            url: '/pages/more/more'
                        });
                    }
                });
            }
        }
    },

    // 拉取列表
    getAll() {
        let that = this;

        var p = {
            m: 'index',
            uid: that.data.z_uid
        };

        post(p).then(res => {
            // console.log(res)
            if (res.r == 0) {
                if (res.z_check == 0) {
                    let url = '/pages/reward/reward?uid=' + that.data.m_uid + '&from=xlist';
                    wx.navigateTo({
                        url: url
                    });
                } else {
                    that.setData({
                        list: res,
                        show_count_money: res.show_count_money
                    });

                    var jq = wx.getStorageSync('jq');
                    if (jq) {
                        var ye = parseInt(res.count_money - jq);
                        var yey = parseInt(ye) / 100;
                        if (yey > 0) {

                            wx.showModal({
                                showCancel: false,
                                content: '恭喜获得收益：' + yey + '元，再接再厉哦~',
                            });
                            /*that.setData({
                              flag: true,
                              sy: yey
                            });*/
                        }
                        wx.setStorageSync('jq', res.count_money);
                    } else {
                        wx.setStorageSync('jq', res.count_money);
                    }
                }
            }
        });
    },

    close_sy() {
        /*this.setData({
          flag: false
        });*/
    },
    // 去试玩

    demoGain: function(event) {
        let that = this;
        let url = '/pages/jump/jump?pls=wx&uid=' + that.data.m_uid + '&weappid=' + event.target.dataset.weappid + '&from=xlist';
        wx.navigateTo({
            url: url
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let that = this;

        var z_uid = wx.getStorageSync("z_uid"); // 对应赚客手机号
        var m_uid = wx.getStorageSync("m_uid"); // 对应赚客用户uid
        if (z_uid && m_uid) {
            that.setData({
                z_uid: z_uid,
                m_uid: m_uid
            });
            that.getAll();


            var pq = {
                m: 'put_money',
                uid: that.data.z_uid
            };
            post(pq).then(res => {
                that.setData({
                    result: res.result
                });
                that.run()
            })
        };
    },
    run() {
        let that = this;

        // 文字轮播
        var result = that.data.result
        var WrittenBy = [];
        var csj = that.data.marqueeDistance2;
        var hahah
        if ((result.length - csj) < 10) {
            hahah = result.length - csj
        }
        if (csj > result.length) {
            that.setData({
                marqueeDistance2: 0,
            });
            csj = 0;
            // return
        } else {
            hahah = 10
        }
        for (var i = 0; i < hahah; i++) {
            var ccc = csj + i
            WrittenBy.push(result[ccc])
        }
        that.setData({
            WrittenBy: WrittenBy,
        });
        var query = wx.createSelectorQuery();
        query.select('.every').boundingClientRect(function(rect) {
            if (rect) {
                var width = rect.width
                var windowWidth = wx.getSystemInfoSync().windowWidth;
                // console.log(width)
                // console.log(windowWidth)

                that.setData({
                    width: width,
                    windowWidth: windowWidth
                });
                that.run1();
            }
        }).exec();

    },
    run1: function() {
        var that = this;
        var interval = setInterval(function() {
            if ((-that.data.marqueeDistance + that.data.windowWidth) < that.data.width) {
                that.setData({
                    marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
                });
            } else {
                clearInterval(interval);
                var nce2 = that.data.marqueeDistance2 + 10
                that.setData({
                    marqueeDistance2: nce2,
                    marqueeDistance: 0
                });
                that.run();
            }
        }, that.data.interval);
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    showfx: function(res) {
        let that = this;
        // console.log(res)
        this.setData({
            title: res.currentTarget.dataset.title,
            imageUrl: res.target.dataset.image,
            weappid: res.currentTarget.dataset.weappid,
            doc: res.currentTarget.dataset.doc,
            share_wxfx: false
        });
        wx.setClipboardData({
            data: that.data.doc,
            success() {
                wx.showToast({
                    title: '文案复制成功',
                    icon: 'success'
                });
            }
        })
    },

    onShareAppMessage: function(res) {
        // console.log(this.data.weappid)
        let that = this;
        if (res.from === 'button') {
            // 来自页面内转发按钮
            let url = '/pages/jump/jump?uid=' + that.data.m_uid + '&weappid=' + that.data.weappid
            return {
                title: that.data.title,
                path: url,
                imageUrl: that.data.imageUrl,
                success: (res) => {

                }
            }
        }
    },
    share_circle(rimg) {
        let that = this;
        // console.log(that.data.doc)
        that.setData({
            share_wx_bg: true,
            share_img: false
        })
        wx.showLoading({
            title: "加载中",
            mask: true,
            success: (result) => {}
        });

        let p = {
            m: 'share',
            uid: that.data.z_uid,
            weappid: that.data.weappid,
            ua: 'wechat',
            flag: 1,
        }
        post(p).then(res => {
            let image_pyq = JSON.parse(res.result).toString()
            that.setData({
                image_pyq: image_pyq
            })
        })

    },
    imageLoading(ev) {
        if (ev.detail.height > 0 && ev.detail.width > 0) {
            wx.hideLoading();
            this.setData({
                ifName: false,
                share_img: false
            });
        }
    },
    share_circle_bc() {
        let that = this;
        wx.downloadFile({
            url: that.data.image_pyq,
            success: function(res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function(data) {
                        wx.showModal({
                            title: '保存成功',
                            content: '文案复制成功，文案图片已自动生成并保存到您的相册，可进入朋友圈分享',
                            showCancel: false,
                            success: function(res) {
                                if (res.confirm) {}
                            },
                            fail: function(res) {

                            }
                        })

                    }
                })
            }
        })
    },
    share_wx_zz() {
        let that = this;
        that.setData({
            share_wxfx: true,
            share_img: true,
            ifName: true,
            share_wx_bg: false,
            image_pyq: ''
        })
    },
    submitFormId(e) {
        let that = this;
        let formId = e.detail.formId;
        let button = e.detail.target.dataset.name;
        let page = getCurrentPageUrlWithArgs();
        let p = {
            m: 'colform',
            uid: that.data.m_uid,
            openid: wx.getStorageSync('weapp_openid'),
            formId: formId,
        }
        if (page && page.length > 0) {
            p.page = page;
        }
        if (button && button.length > 0) {
            p.button = button;
        }
        //console.log(p);
        post(p).then(res => {})
    },
    preventTouchMove() {

    }
})